package net.ojbk.sso.center.web.handlers;

import net.ojbk.sso.center.beans.pojo.ClientWebSystem;
import net.ojbk.sso.center.beans.pojo.TokenSystem;
import net.ojbk.sso.center.service.SsoService;
import net.ojbk.sso.core.beans.dto.DTO_TO_Center;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

/**
 * Created with IntelliJ IDEA.
 * User: twobox
 * Date: 2019/4/8
 * Time: 15:11
 * Description: No Description
 */
@Controller
@RequestMapping("/sso")
public class SsoController {
    private static Logger logger = Logger.getLogger(SsoController.class);
    @Autowired
    private SsoService ssoService;
    @Autowired
    private ClientWebSystem clientWebSystem;
    @Autowired
    private TokenSystem tokenSystem;

    @RequestMapping(value = "")
    public ResponseEntity<Object> sso(HttpSession session, @RequestBody DTO_TO_Center dto_to_center) throws Exception {
        logger.debug("Get new ClientRequest：" + dto_to_center);
        // 验证请求的合法性
        if (!clientWebSystem.isLegalDTO(dto_to_center))
            throw new Exception("ClientWebsite is not legal.");

        switch (dto_to_center.getType()) {
            case 1:
                return login(dto_to_center);
            case 2:
                return getUid(dto_to_center);
            default:
                throw new Exception("The request's type is not found.");
        }
    }

    // 1.1登陆一个网站
    public ResponseEntity<Object> login(DTO_TO_Center dto_to_center) throws Exception {
        tokenSystem.loginAWeb(dto_to_center.getToken(), clientWebSystem.getClientWebsite_ByCname(dto_to_center.getCname()));
        logger.debug("ClientWebsite's Info ：I want " + dto_to_center.getToken() + " to login the " + dto_to_center.getCname());
        return new ResponseEntity<>("success.", HttpStatus.OK);
    }

    // 1.2获取uid
    public ResponseEntity<Object> getUid(DTO_TO_Center dto_to_center) throws Exception {
        return new ResponseEntity<>(ssoService.getUid(dto_to_center.getToken()), HttpStatus.OK);
    }
}
